package com.situ.gym.interceptor;

import com.situ.gym.util.JwtUtil;
import com.situ.gym.util.ThreadLocalUtil;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.web.servlet.HandlerInterceptor;

import java.util.Map;

public class LoginInterceptor implements HandlerInterceptor {


    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String token = request.getHeader("Authorization");
        
        // 如果token为空，直接返回401
        if (token == null || token.trim().isEmpty()) {
            response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
            return false;
        }
        
        //验证这个令牌
        try {
            //令牌是伪造的或者令牌过期，都会抛出异常
            Map<String, Object> map = JwtUtil.parseToken(token);
            ThreadLocalUtil.set(map);

            //放行
            return true;
        } catch (Exception e) {
            //http的响应状态，改成401
            response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
            //不放行
            return false;
        }
    }
}
